package sistemadeproyectos;

import java.sql.*;
import org.postgresql.Driver;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import java.awt.Image;

public class RegistrarUsuario extends javax.swing.JDialog {

    /** Creates new form RegistrarUsuario */
    public RegistrarUsuario(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.getRootPane().setDefaultButton(jbtnAceptar);
        jtxtUsuario.requestFocus();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jtxtUsuario = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jpwfClave = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jbtnExaminar = new javax.swing.JButton();
        jbtnAceptar = new javax.swing.JButton();
        jbtnCancelar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jpwfConfirmar = new javax.swing.JPasswordField();
        jtxtAvatar = new javax.swing.JTextField();
        jlblNombre = new javax.swing.JLabel();
        jlblImagen = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sistemadeproyectos.SistemadeproyectosApp.class).getContext().getResourceMap(RegistrarUsuario.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jtxtUsuario.setText(resourceMap.getString("jtxtUsuario.text")); // NOI18N
        jtxtUsuario.setName("jtxtUsuario"); // NOI18N

        jtxtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jtxtUsuarioKeyReleased(evt);
            }
        });

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jpwfClave.setText(resourceMap.getString("jpwfClave.text")); // NOI18N
        jpwfClave.setName("jpwfClave"); // NOI18N

        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setFont(resourceMap.getFont("jLabel4.font")); // NOI18N
        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setToolTipText(resourceMap.getString("jLabel4.toolTipText")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jbtnExaminar.setText(resourceMap.getString("jbtnExaminar.text")); // NOI18N
        jbtnExaminar.setName("jbtnExaminar"); // NOI18N
        jbtnExaminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExaminarActionPerformed(evt);
            }
        });

        jbtnAceptar.setText(resourceMap.getString("jbtnAceptar.text")); // NOI18N
        jbtnAceptar.setName("jbtnAceptar"); // NOI18N
        jbtnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAceptarActionPerformed(evt);
            }
        });

        jbtnCancelar.setText(resourceMap.getString("jbtnCancelar.text")); // NOI18N
        jbtnCancelar.setName("jbtnCancelar"); // NOI18N
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        jLabel5.setFont(resourceMap.getFont("jLabel5.font")); // NOI18N
        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jpwfConfirmar.setText(resourceMap.getString("jpwfConfirmar.text")); // NOI18N
        jpwfConfirmar.setToolTipText(resourceMap.getString("jpwfConfirmar.toolTipText")); // NOI18N
        jpwfConfirmar.setName("jpwfConfirmar"); // NOI18N

        jtxtAvatar.setEditable(false);
        jtxtAvatar.setText(resourceMap.getString("jtxtAvatar.text")); // NOI18N
        jtxtAvatar.setName("jtxtAvatar"); // NOI18N

        jlblNombre.setText(resourceMap.getString("jlblNombre.text")); // NOI18N
        jlblNombre.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jlblNombre.setName("jlblNombre"); // NOI18N

        jlblImagen.setText(resourceMap.getString("jlblImagen.text")); // NOI18N
        jlblImagen.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jlblImagen.setName("jlblImagen"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jtxtUsuario)
                            .addComponent(jpwfClave)
                            .addComponent(jpwfConfirmar, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jtxtAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jbtnExaminar, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jbtnAceptar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jbtnCancelar)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(36, 36, 36)
                                .addComponent(jlblNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jlblImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(31, 31, 31)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(184, 184, 184))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jLabel1)
                        .addGap(35, 35, 35)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jtxtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jpwfClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jpwfConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jtxtAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jbtnExaminar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jbtnCancelar)
                            .addComponent(jbtnAceptar)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(70, 70, 70)
                        .addComponent(jlblNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jlblImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private ImageIcon ajustarImagen(String ico, int alto, int ancho) {
        ImageIcon tmpIconAux = new ImageIcon(ico);
        //Escalar Imagen
        ImageIcon tmpIcon = new ImageIcon(tmpIconAux.getImage().getScaledInstance(ancho, alto, Image.SCALE_DEFAULT));
        return tmpIcon;
    }
    
    private String pasarURL(String URL){
        String nuevaURL = "";
        if(System.getProperty("os.name").substring(0,5).equals("Windo")){
            int i = 0;
            while(i < URL.length()){
                nuevaURL = nuevaURL + URL.charAt(i);
                if((""+URL.charAt(i)).equals("\\")){
                    nuevaURL = nuevaURL + URL.charAt(i);
                }
                i++;
            }
            //System.out.println("Final: " + nuevaURL);
        }
        else{
            nuevaURL = URL;
        }
        return nuevaURL;
    }
    
    private void jbtnExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExaminarActionPerformed
        // TODO add your handling code here:
        JFileChooser fileChooser = new JFileChooser();   
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos de imagen: JPG & GIF", "jpg", "gif");
        fileChooser.setFileFilter(filter);
        fileChooser.setAcceptAllFileFilterUsed(false);
        int result = fileChooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION ){
            String name = fileChooser.getSelectedFile().getPath();
            jtxtAvatar.setText(name);
            jlblImagen.setIcon(ajustarImagen(name, jlblImagen.getHeight(), jlblImagen.getWidth()));
        }
    }//GEN-LAST:event_jbtnExaminarActionPerformed

    private void jbtnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAceptarActionPerformed
        // TODO add your handling code here:
        String nombre = "";
        String clave = "";
        String url_avatar = "";
        String login = "";
        boolean completo = false;
        boolean repetido = false;
        
        if(jtxtUsuario.getText().equals("")){
            JOptionPane.showMessageDialog(null, "El nombre de usuario no puede ser vacio", "Datos incompletos", JOptionPane.ERROR_MESSAGE);
            jtxtUsuario.requestFocus();
        }
        else if(jpwfClave.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Clave vacia", "Datos incompletos", JOptionPane.ERROR_MESSAGE);
            jpwfClave.requestFocus();
        }
        else if(jpwfConfirmar.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Clave confirmacion vacia", "Datos incompletos", JOptionPane.ERROR_MESSAGE);
            jpwfConfirmar.requestFocus();
        }
        else if(jtxtAvatar.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Introduzca una imagen de avatar", "Datos incompletos", JOptionPane.ERROR_MESSAGE);
            jbtnExaminar.requestFocus();
        }
        else{
            if(jpwfClave.getText().equals(jpwfConfirmar.getText())){
                completo = true;
            }
            else{
                JOptionPane.showMessageDialog(null, "Las claves no coinciden", "Confirmar clave", JOptionPane.ERROR_MESSAGE);
            }
        }
        if(completo == true){
            try{
                BDAdmin motor = new BDAdmin("SELECT * FROM USUARIO");
                ResultSet rs = motor.consulta();
                while (rs.next()) {
                    login = rs.getString("NOMBRE");
                    if(login.equals(jtxtUsuario.getText())){
                        repetido = true;
                        JOptionPane.showMessageDialog(null, "El nombre de usuario " + jtxtUsuario.getText() + " no está disponible", "Usuario repetido", JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                }  

                if (repetido == false){
                    nombre = jtxtUsuario.getText();
                    clave = String.valueOf(jpwfClave.getPassword());
                    url_avatar = pasarURL(jtxtAvatar.getText());
                    motor.setQuery("INSERT INTO USUARIO VALUES ('" + nombre + "','" + clave + "','" + url_avatar +"')");
                    motor.actualizar();
                    JOptionPane.showMessageDialog(null, "¡" + jtxtUsuario.getText() + " bienvenid@ al Sistema Colaborativo de Proyectos!", "Registro exitoso", JOptionPane.INFORMATION_MESSAGE);
                    UnirseEquipo unir = new UnirseEquipo();
                    Usuario creado = new Usuario();
                    creado.setUsuario(nombre);
                    creado.setClave(clave);
                    creado.setURL_Avatar(url_avatar);
                    unir.setUsuario(creado);
                    unir.setVisible(true);
                    ((javax.swing.JFrame)this.getParent()).dispose();
                    this.dispose();
                }
                motor.cerrar();
            }
            catch(SQLException sqle){
                sqle.printStackTrace();
            }
        }
    }//GEN-LAST:event_jbtnAceptarActionPerformed

    private void jtxtUsuarioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtxtUsuarioKeyReleased
        // TODO add your handling code here:
        jlblNombre.setText(jtxtUsuario.getText());
    }//GEN-LAST:event_jtxtUsuarioKeyReleased

    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jbtnCancelarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            //java.util.logging.Logger.getLogger(prueb.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            //java.util.logging.Logger.getLogger(prueb.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            //java.util.logging.Logger.getLogger(prueb.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            //java.util.logging.Logger.getLogger(prueb.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                RegistrarUsuario dialog = new RegistrarUsuario(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JButton jbtnAceptar;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JButton jbtnExaminar;
    private javax.swing.JLabel jlblImagen;
    private javax.swing.JLabel jlblNombre;
    private javax.swing.JPasswordField jpwfClave;
    private javax.swing.JPasswordField jpwfConfirmar;
    private javax.swing.JTextField jtxtAvatar;
    private javax.swing.JTextField jtxtUsuario;
    // End of variables declaration//GEN-END:variables
}